package com.qianjiangcloud.store.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;
import com.qianjiangcloud.store.ui.pulltorefresh.lib.PullToRefreshBase;
import com.qianjiangcloud.store.ui.pulltorefresh.lib.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.qianjiangcloud.store.R;


/**
 * Created by Jelly on 2016/8/1.
 */
public class AccountAfterSalesFragment extends BaseDoFragment {

    private int page=0;
    private PullToRefreshListView mListView=null;
    private ArrayList<JSONObject> salesList=new ArrayList<JSONObject>();
    private AfterSaleOrderList mAdapter;
    private JsonTask mTask;
    private boolean inloding=false;
    private boolean norme=false;
    //private ImageButton mBack;
    private TextView mRight;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.fragment_after_sales,null);
        mActionBar.setTitle(R.string.after_sale);
       // mActionBar.getBackButton().setVisibility(View.VISIBLE);
        mActionBar.setShowBackButton(true);
        mActionBar.setRightTitleButton(R.string.apply_after_sales, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(AgentActivity.intentForFragment(mActivity,AgentActivity.FRAGMENT_AFTER__SALES_ORDER));
            }
        });
        mListView= (PullToRefreshListView) findViewById(R.id.after_sales_listview);
        mListView.setPullToRefreshEnabled(true);
       // mBack= (ImageButton) findViewById(R.id.action_bar_titlebar_left);
//        mRight= (TextView) findViewById(R.id.tv_right);
//        mRight.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//               // startActivity(AgentActivity.intentForFragment(mActivity,AgentActivity.FRAGMENT_AFTER__SALES_ORDER));
//            }
//        });
//        mBack.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                mActivity.finish();
//            }
//        });

        mAdapter=new AfterSaleOrderList();
        mListView.getRefreshableView().setAdapter(mAdapter);
        mListView.setRefreshing(true);
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener() {

            @Override
            public void onRefresh() {
                loadNextPage(0, false);


            }
            @Override
            public void onRefreshMore() {
            }
        });
        mListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    String orderId=salesList.get(i).optString("return_id");
                    startActivity(AgentActivity.intentForFragment(mActivity,AgentActivity.FRAGMENT_AFTER_DETAILS).
                    putExtra("orderId",orderId));



            }
        });
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                int lastVisiblePosition = firstVisibleItem + visibleItemCount;
                if (lastVisiblePosition + 3 >= mAdapter.getCount()&&!norme&&!inloding) {
                    loadNextPage(page,false);
                    inloding=true;

                }
            }
        });
        loadNextPage(0,true);

    }

    private void loadNextPage(int oldPageNum,boolean isFirst) {
        page = oldPageNum + 1;
        if (page == 1) {
            norme=false;
            salesList.clear();
            inloding=true;
            mAdapter.notifyDataSetChanged();
        } else {
            if (mTask != null && mTask.isExcuting)
                return;
        }
        mTask = new JsonTask();
        Run.excuteJsonTask(mTask, new MyAccountAfterSalesTask(isFirst));

    }


    public class AfterSaleOrderList extends BaseAdapter {

        @Override
        public int getCount() {
            return salesList.size();
        }

        @Override
        public Object getItem(int position) {
            return salesList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = getActivity().getLayoutInflater().inflate(R.layout.fragment_after_sales_list_item, null);
                holder = new ViewHolder();
                holder.tvId= (TextView) convertView.findViewById(R.id.order_id);
                holder.tvTime= (TextView) convertView.findViewById(R.id.apply_time);
                holder.tvState= (TextView) convertView.findViewById(R.id.apply_state);
                holder.tvType= (TextView) convertView.findViewById(R.id.apply_type);
                holder.tvReason= (TextView) convertView.findViewById(R.id.apply_content);
                convertView.setTag(holder);
            }else {
                holder= (ViewHolder) convertView.getTag();
            }
            JSONObject object=salesList.get(position);
            holder.tvId.setText(object.optString("order_id"));

            Long time=Long.valueOf(object.optString("apply_time"));
            Date date=new Date(time*1000);
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            holder.tvTime.setText(format.format(date));

            holder.tvState.setText(object.optString("apply_state"));
            int type=object.optInt("apply_type");
            String applyType="";

            if (type==1){
                applyType="退货";
            }
            if (type==2){
                applyType="换货";
            }
            holder.tvType.setText(applyType);
            holder.tvReason.setText(object.optString("apply_reason"));

            return  convertView;
        }
        class ViewHolder{
            TextView tvId;
            TextView tvTime;
            TextView tvState;
            TextView tvType;
            TextView tvReason;
        }
    }



    public class MyAccountAfterSalesTask implements JsonTaskHandler {
        public boolean isFirst;
        public MyAccountAfterSalesTask(){}
        public MyAccountAfterSalesTask(boolean isFirst){
            this.isFirst=isFirst;
        }

        @Override
        public void task_response(String json_str) {
            hideLoadingDialog();
            mListView.onRefreshComplete();
            try {
                JSONObject all=new JSONObject(json_str);
                if (Run.checkRequestJson(mActivity,all)){
                    JSONObject data=all.optJSONObject("data");
                    int total=data.optInt("total");
                    JSONArray child=data.getJSONArray("data");
                    if (child!=null&&child.length()>0){
                        for (int i=0;i<child.length();i++){
                            salesList.add(child.getJSONObject(i));
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                    Log.i("test","totle"+total+"-----"+salesList.size());
                    if (salesList.size()>=total){
                        norme=true;
                    }

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            inloding=false;

        }

        @Override
        public JsonRequestBean task_request() {
            if (isFirst) {
                showCancelableLoadingDialog();
            }
            JsonRequestBean req=new JsonRequestBean("mobileapi.aftersales.getall");
            req.addParams("n_page",String.valueOf(page));
            return req;
        }
    }




}
